import React, { useEffect, useState } from 'react';
import { Button, Form, Input, Modal, message } from 'antd';
import type { FormProps } from 'antd';
import "./style.css"
import Login1 from '../../assets/Login1.jpg'
import { useNavigate } from 'react-router-dom';

import axios from 'axios';

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};
const Index: React.FC = () => {
  const navigate = useNavigate()
  // 弹出登录注册框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isLoginMode, setIsLoginMode] = useState(true); // 状态控制登录或注册模式
  const [userName, setUserName] = useState<string | null>(null); // 新增状态来存储用户名
  const [photoImg, setPhotoImg] = useState<string | null>(null); // 新增状态来存储用户头像
  useEffect(() => {
    const storedUserInfo = localStorage.getItem("userInfor");
    if (storedUserInfo) {
      const { username, photoImg } = JSON.parse(storedUserInfo);
      setUserName(username);
      setPhotoImg(photoImg);
    }
  }, []);

  const handelOut = () => {
    localStorage.removeItem("token");
    localStorage.removeItem("userInfor");
    setUserName(null);
    setPhotoImg(null);
    navigate("/");
  };

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    const endpoint = isLoginMode ? "/api/login" : "/api/sigin"; // 根据模式选择API
    axios.post(endpoint, values).then((resp) => {
      console.log(resp, 'sdfghj');
      const { code, msg, userinfor, token } = resp.data;
      if (code === 200) {
        message.success(msg);
        setUserName(userinfor.username);
        setPhotoImg(userinfor.photoImg);
        localStorage.setItem("userInfor", JSON.stringify(userinfor));
        localStorage.setItem("token", token);
        navigate("/");
        handleOk();
      } else {
        message.error(msg);
      }
    });
  };

  const handleRegisterClick = () => {
    setIsLoginMode(false); // 切换到注册模式
  };


  return (
    <div>
      {/* 根据用户是否登录显示不同的按钮 */}
      {
        userName ? (
          <div className='Headerimg'>
            <img onClick={() => navigate('../../User')} src={photoImg ?? ""} alt="avatar" />
            <p className='header-name'>{userName}</p>
            <button className='LoginOut' onClick={handelOut}>退出登录</button>
          </div>
        ) : (
          <button className="LogineBtn" onClick={showModal}>
            登录注册
          </button>
        )
      }

      {/* 登录注册弹框 */}
      <Modal footer={null} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} width={700}>
        <div className="LoginBox">
          <div className="LoginLeft">
            <img src={Login1} alt="" />
          </div>
          <div className="LoginRight">
            <div className="Nav"></div>
            <div className="LoginCon">
              <div className="LoginTitle">
                <p>{isLoginMode ? "账号密码登录" : "账号注册"}</p>
              </div>
              <div className="Loginbott">
                <Form
                  name="basic"
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 16 }}
                  style={{ maxWidth: 600 }}
                  initialValues={{ remember: true }}
                  onFinish={onFinish}
                  autoComplete="off"
                >
                  <Form.Item<FieldType>
                    label=""
                    name="username"
                    style={{ height: 40 }}
                    rules={[{ required: true, message: '请输入正确手机号码' }]}
                  >
                    <Input placeholder='请输入邮箱/手机号' />
                  </Form.Item>

                  <Form.Item<FieldType>
                    label=""
                    name="password"
                    rules={[{ required: true, message: '请输入正确手机密码' }]}
                  >
                    <Input.Password placeholder='请输入密码' />
                  </Form.Item>
                  <Form.Item>
                    <ul className='LoginUl'>
                      <li><a href="#">手机验证码登录</a></li>
                      <li><a href="#">忘记密码</a></li>
                    </ul>
                  </Form.Item>
                  <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                    <Button type="primary" htmlType="submit">
                      {isLoginMode ? "登录" : "注册"}
                    </Button>
                  </Form.Item>
                </Form>
              </div>
            </div>
            <div className="LoginBott">
              <div className="Bottnav">
                <p>——其他登录方式——</p>
              </div>
              <div className="Bottimg">
                <a href="#"><img src="https://img0.baidu.com/it/u=3126757857,223977411&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500" alt="" /></a>
                <a href="#"><img src="https://img1.baidu.com/it/u=328941353,708007735&fm=253&fmt=auto&app=138&f=PNG?w=625&h=500" alt="" /></a>
                <a href="#"><img src="https://img0.baidu.com/it/u=3162509099,3350821350&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500" alt="" /></a>
                <a href="#"><img src="https://img1.baidu.com/it/u=3928456370,651735129&fm=253&fmt=auto&app=138&f=JPEG?w=616&h=500" alt="" /></a>
                <a href="#"><img src="https://img1.baidu.com/it/u=1242840031,555345420&fm=253&fmt=auto&app=120&f=PNG?w=500&h=500" alt="" /></a>
                <a href="#"><img src="https://img2.baidu.com/it/u=3655985736,3474524930&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800" alt="" /></a>
              </div>
              <div className="BottZc">
                <p>登录即同意<a href="#">用户协议</a>和<a href="#">隐私政策</a></p>
                {/* 注册切换链接 */}
                {!isLoginMode && (
                  <div className='ZCing'>
                    <a href="#" onClick={() => setIsLoginMode(true)}>已有账户，点击登录</a>
                  </div>
                )}
                {isLoginMode && (
                  <div>
                    <a href="#" onClick={handleRegisterClick}>手机号注册</a>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </Modal>
    </div>
  )
}

export default Index
